package com.ypz.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ypz.reggie.common.CustomException;
import com.ypz.reggie.common.MyBaseContext;
import com.ypz.reggie.entity.*;
import com.ypz.reggie.mapper.OrdersMapper;
import com.ypz.reggie.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;

    /**
     * 用户下单
     *
     * @param orders
     */
    @Override
    @Transactional//事物控制，操作多张表
    public void submit(Orders orders) {
        //获取当前用户id
        Long currentId = MyBaseContext.getCurrentId();

        //查询当前用户的购物车信息
        LambdaQueryWrapper<ShoppingCart> lqwShoppingCart = new LambdaQueryWrapper<>();
        lqwShoppingCart.eq(currentId != null, ShoppingCart::getUserId, currentId);

        List<ShoppingCart> shoppingCartList = shoppingCartService.list(lqwShoppingCart);

        if (shoppingCartList == null) {
            throw new CustomException("购物车为空不能下单");
        }

        //查询用户信息
        User user = userService.getById(currentId);

        //查询用户地址
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);

        if (addressBook == null) {
            throw new CustomException("地址为空不能下单");
        }

        //使用MyBatisPlus的工具生产订单号
        long orderId = IdWorker.getId();//订单号

        //在后端再计算一边总金额，使用AtomicInteger，而不是Integer是为了保证在高并发，多线程的情况下也不出差
        AtomicInteger amount = new AtomicInteger(0);

        //设置订单详情OrderDetail里的数据
        List<OrderDetail> orderDetails = shoppingCartList.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            //设置订单id
            orderDetail.setOrderId(orderId);
            //设置单品数量
            orderDetail.setNumber(item.getNumber());
            //设置口味
            orderDetail.setDishFlavor(item.getDishFlavor());
            //设置菜品id
            orderDetail.setDishId(item.getDishId());
            //设置套餐id
            orderDetail.setSetmealId(item.getSetmealId());
            //设置菜品或套餐名称
            orderDetail.setName(item.getName());
            //设置图片路径
            orderDetail.setImage(item.getImage());
            //设置单品价格
            orderDetail.setAmount(item.getAmount());
            //计算总价格=单品价格x单品数量
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());


        //设置订单Orders信息
        //设置订单id，这个是主键值
        orders.setId(orderId);
        //设置下单时间
        orders.setOrderTime(LocalDateTime.now());
        //设置结账时间
        orders.setCheckoutTime(LocalDateTime.now());
        //设置状态//订单状态 1待付款，2待派送，3已派送，4已完成，5已取消
        orders.setStatus(2);
        //设置总金额
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        //设置当前用户id
        orders.setUserId(currentId);
        //设置订单id
        orders.setNumber(String.valueOf(orderId));
        //设置用户的姓名,因为没有用户姓名，用收货人代替
     //   orders.setUserName(user.getName());
        orders.setUserName(addressBook.getConsignee());
        //设置收货人
        orders.setConsignee(addressBook.getConsignee());
        //设置收货人电话号码
        orders.setPhone(addressBook.getPhone());
        //设置地址
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));

        //向订单表插入数据，只需要插入一条,向订单插入数据时还需要用户的其他信息和地址信息
        this.save(orders);

        //向订单明细表插入数据，可能是一条或多条
        orderDetailService.saveBatch(orderDetails);

        //清空购物车
        shoppingCartService.remove(lqwShoppingCart);
    }
}

























